// area-life.js
Page({
  data: {
    currentTab: 'life',
    LifeNotes: [],  // 当前分区的笔记数据
    randomNote: {}, // 随机笔记
    areaMap: {      // Tab与分区ID的映射关系
      life: 0,
      study: 1,
      interpersonal: 2
    }
  },

  onLoad() {
    this.loadNotes();
  },

  // 加载笔记数据
  loadNotes() {
    const that = this;
    const areaID = this.data.areaMap[this.data.currentTab];
    console.log('[AreaID] areaID:', areaID); // 添加日志
    
    const currentUser = wx.getStorageSync('currentUser');
  if (!currentUser || !currentUser.userID) {
    wx.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
    
    wx.request({
      
      url: `http://localhost:8848/Note/area/${areaID}`,
      method: 'GET',
    
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token') || ''}` // 从本地存储获取 Token
    },
      
      success(res) {
        
        console.log('当前 Token:', wx.getStorageSync('token'));
        console.log('[接口响应]', res.data); // 打印完整响应数据
        console.log('[DEBUG] 数据类型检查:', {
          statusCode: res.statusCode,
          serverUser: res.data,
          passwordExists: !!res.data.password,
          passwordType: typeof res.data.password
        });
        if (res.statusCode === 200 && res.data) {
          // 从 serverUser 字段提取数据（或直接使用 res.data）
        const rawNotes = res.data.serverUser || res.data;
          // 过滤无效数据
        const validNotes = rawNotes.filter(note => note && note.notetime != null);
         
        const notes = validNotes.map(note => ({
            ...note,
          })).sort((a, b) => new Date(b.notetime) - new Date(a.notetime));

          that.setData({
            LifeNotes: notes,
            randomNote: notes.length > 0 ? 
              notes[Math.floor(Math.random() * notes.length)] : {}
          });
        }
      },
      fail(err) {
        console.error('请求失败:', err);
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    });
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab,
      LifeNotes: [], // 清空旧数据
      randomNote: {}
    }, () => {
      this.loadNotes(); // Tab切换后重新加载数据
    });
  },
  
  /*
    添加按钮点击事件
  */
  handleAdd(){
    wx.navigateTo({ url: '/pages/addNote/addNote' });
  },

  handleSearch(){
    wx.navigateTo({ url: '/pages/search/search', })
  },

  handleNote: function(e) {
    let notenum = e.currentTarget.dataset.notenum;
    wx.navigateTo({
      url: `/pages/note/note?notenum=${notenum}`,
    })
  }
})